package com.wangyadong.hobby.nio.charter2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port) {

        this.port = port;
    }

    public void start() throws InterruptedException {
        //指定使用NioEventLoopGroup 接受，处理连接
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            //#1 Bootstraps the server
            ServerBootstrap b = new ServerBootstrap();
            //#2   Specifies NIO transport, local socket address  NioServerSocketChannel指定为NIO Channel,并且绑定端口
            b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
                    //#3 Adds handler to channel pipelin ，这里应该用的监听器，接受每一个请求
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //处理
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //#4 Binds server, waits for server to close, and releases resources

                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture f = b.bind(port).sync();
            System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());

//            f.channel().closeFuture().sync();
        } finally {
//            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        System.out.println("====");
//        Integer integer = Integer.valueOf(args[0]);
        new EchoServer(16).start();
    }
}
